import * as React from 'react'
import { parse } from 'query-string'
import { getWordData } from 'service/index'
import { Spin, Icon, Row, Col } from 'antd'
import Tags from 'components/Tags'

import './index.less'
import { arch } from 'os';

interface Prop {
  history: any
}

interface State {
  showAll: boolean,
  showLoading: boolean,
  showOpenButton: boolean,
  kw: string,
  wordInfo: object | null,
  wordTitle: string,
  tags: any[],
  languageType: string
}

export default class Main extends React.Component<Prop, State> {
  descRef = null
  constructor(props, context) {
    super(props, context);
    const kw = parse(props.location.search).kw
    this.state = {
      showAll: false,
      showOpenButton: false,
      showLoading: false,
      kw,
      wordInfo: {},
      wordTitle: '',
      tags: [],
      languageType: ''
    }
  }

  componentDidMount() {
    try {
      // 提供全局方法，重置路由
      (window as any).changeRoute = (text) => {
        this.props.history.push('/word')
      }
      // 注册window全局方法给后台调用
      (window as any).webViewCallback = (text) => {
        let type = 'other'
        if (/[\u4e00-\u9fa5]/.test(text)) {
          type = 'chinese'
        }
        this.setState({
          wordTitle: text,
          languageType: type
        }, () => {this.getData(text)})
        // this.getData(text)
      }
    } catch (error) {
    }
    if (this.descRef) {
      let contentHeight = this.descRef.scrollHeight
      this.setState({ // 高度太小的时候就不启用展开收起功能
        showOpenButton: contentHeight < 54 ? false : true
      })
    }
    // setTimeout(webViewCallback('测试次'), 3000)
    // setTimeout(webViewCallback('french'), 3000)
  }

  componentDidCatch(error, info) {
    console.log(error, info);
  }
  // 获取查词信息
  getData = async kw => {
    this.setState({
      showLoading: true
    })
    try {
      const data = await getWordData(kw)
      // const data = {
      //   "result":
      //     {
      //       "id": 1,
      //       "mainId": "1501D",
      //       "subId": "141D",
      //       "intro": "很长的简介很长的简介很长的简介很长的简介很长的简",
      //       "chinese":"超声",
      //       "english":"this is a English",
      //       // "english":"EnglishEnglishEnglishEnglishEnglishEnglishEn很重的中英文很长中文hEn很重的中英文很长中hEn很重的中英文很长中结果",
      //       "japanese":"japanese",
      //       // "french":"french",
      //       "german":"german",
      //       "yongXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
      //       // "daiXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
      //       "daiXiang": [],
      //       "shuXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
      //       "fenXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
      //       "canXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
      //       "pinYin": "拼音",
      //       "shortPinyin": "简拼",
      //       "description": "说明",
      //       "creationTime": "时间",
      //       "remark": "备注",
      //     },
      // "error":null,
      // "success": true
      // }
      let tag = []
      if (data.result) {
        const { english , japanese, french, german}: any = data.result
        if (japanese) {
          tag.push({tag: 'japanese', content: japanese, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (english) {
          tag.push({tag: 'english', content: english, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (french) {
          tag.push({tag: 'french', content: french, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (german) {
          tag.push({tag: 'german', content: german, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
      }
      this.setState({
        kw,
        wordInfo: data.result,
        showLoading: false,
        tags: tag
      }, ()=> {
          try {
            if (data.result) {
              dotNetMessage.showwindow('querydata')
            } else {
              dotNetMessage.showwindow('querynodata')
            }
          } catch (error) {

          }})
    } catch (error) {
    }
  }

  handleEdit = () => {
    const { kw } = this.state
    this.props.history.push(`/wordedit?type=edit&kw=${kw}`)
    try {
      dotNetMessage.showwindow('modify')
    } catch (error) {
    }
  }
  handleCreate = () => {
    const { kw } = this.state
    this.props.history.push(`/wordedit?type=create&kw=${kw}`)
    try {
      dotNetMessage.showwindow('create')
    } catch (error) {
    }
  }

  // 展开显示更多
  changeShowInfo = () => {
    this.setState({
      showAll: !this.state.showAll
    })
  }

  // 获取各个项 的数据
  getItems = arr => {
    let newArr = ''
    arr.forEach((item, index) => {
      if (index === arr.length - 1) {
        newArr = newArr + item.word
      } else {
        newArr = newArr + `${item.word} | `
      }
    })
    return newArr
  }

  // 获取小语种
  getOtherLanguage = () => {
    const {japanese, french, german, english}: any = this.state.wordInfo
    if (this.state.kw === japanese) {
      return <span><Col span={2} className="tip">日</Col><Col span={22} className="text" title={japanese}> {japanese}</Col></span>
    }
    if (this.state.kw === french) {
      return <span><Col span={2} className="tip">法</Col><Col span={22} className="text" title={french}> {french}</Col></span>
    }
    if (this.state.kw === german) {
      return <span><Col span={2} className="tip">德</Col><Col span={22} className="text" title={german}> {german}</Col></span>
    }
    if (this.state.kw === english) {
      return <span><Col span={2} className="tip">英</Col><Col span={22} className="text" title={english}> {english}</Col></span>
    }
    return <span></span>
  }

  public render() {
    const { wordInfo, showOpenButton, showLoading, wordTitle, languageType }: any = this.state
    let tags  = this.state.tags.filter(tag => tag.content !== this.state.kw)
    const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />
    return (
      <div className="page-knowledge-card">
        {/* <Spin spinning={showLoading}> */}
        <div className="triangle">
          <div className="logo"><img src="assets/images/logo.png" alt=""/></div>
        </div>
        <div className="word-title">{wordInfo && wordInfo.chinese ? wordInfo.chinese : wordTitle}</div>
        {wordInfo && Object.keys(wordInfo).length > 0 && <div className="have-data">
          <div className="scroll-wrap">
            <div className="chinses-spell">{wordInfo.pinYin ? `[${wordInfo.pinYin}]`: ''}</div>
            {languageType !== 'chinese' &&<Row className="english-spell">{this.getOtherLanguage()}</Row>}
            {wordInfo.intro && <div className="describe">
              <div className={this.state.showAll ? 'content on' : 'content close'} ref={ref => this.descRef = ref}>
                {wordInfo.intro}
              </div>
              {showOpenButton && <div className="on-off" onClick={this.changeShowInfo}>
                <span>{this.state.showAll ? '收起' : '展开全部内容'}</span><img src="assets/images/chevron-down.svg" alt="" />
              </div>}
            </div>}
            <div className="info-box">
              <Row className="li">
                <Col span={4}><span className="title">主范畴</span></Col>
                <Col span={20}><span className="content">{wordInfo.mainId ? wordInfo.mainId: '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">用项</span></Col>
                <Col span={20}><span className="content">{wordInfo.yongXiang && wordInfo.yongXiang.length > 0 ? this.getItems(wordInfo.yongXiang) : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">代项</span></Col>
                <Col span={20}><span className="content">{wordInfo.daiXiang && wordInfo.daiXiang.length > 0 ? this.getItems(wordInfo.daiXiang) : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">属项</span></Col>
                <Col span={20}><span className="content">{wordInfo.shuXiang && wordInfo.shuXiang.length > 0 ? this.getItems(wordInfo.shuXiang) : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">分项</span></Col>
                <Col span={20}><span className="content">{wordInfo.fenXiang && wordInfo.fenXiang.length > 0 ?this.getItems(wordInfo.fenXiang) : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">参项</span></Col>
                <Col span={20}><span className="content">{wordInfo.canXiang && wordInfo.canXiang.length > 0 ? this.getItems(wordInfo.canXiang) : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">简拼</span></Col>
                <Col span={20}><span className="content">{wordInfo.shortPinyin && wordInfo.shortPinyin.length > 0 ? wordInfo.shortPinyin : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">说明</span></Col>
                <Col span={20}><span className="content">{wordInfo.description ? wordInfo.description : '-'}</span></Col>
              </Row>
              <Row className="li">
                <Col span={4}><span className="title">语言</span></Col>
                <Col span={20}><span className="content">
                  {tags && tags.length > 0 ?  <Tags tags={tags} closable={false}/> : '-'}
                </span></Col>
              </Row>
            </div>
          </div>
          <div className="footer">
            <span className="edit-wrap" onClick={this.handleEdit}>
            <img src="assets/images/edit.svg" alt="" />
            <div>编辑该词条</div>
            </span>
          </div>
        </div>}
        {!(wordInfo && Object.keys(wordInfo).length > 0 ) && <div className="no-data">
          <div className="tips">尚未收录词条该词条，欢迎您来创建。</div>
          <div className="create-button" onClick={this.handleCreate}>
            我来创建
          </div>
        </div>}
        {/* </Spin> */}
      </div>
    )
  }
}
